var colors = new Array("lime","red","blue");
var colorPos = 0;

// ******* User Marker extend GMarker(point, icon)

function UserMarker(point, xmlData) {      
  // store the marker data
  this.mrkData = xmlData;
  // marked by mark & sweep?
  this.marked = true;
  this.selected = false;  
  
  GMarker.call(this, point);      
}

function UserMarker(point, xmlData, icon) {      
  // store the marker data
  this.mrkData = xmlData;
  // marked by mark & sweep?
  this.marked = true;
  this.selected = false;  
  
  GMarker.call(this, point, icon);      
}    

UserMarker.prototype = new GMarker(new GLatLng(0,0));
UserMarker.prototype.setData = function(xmlData) {
  this.mrkData = xmlData;
  this.marked = true;
}

UserMarker.prototype.parse = function(data){
  var coords = data.split(","); 
  this.mrkData["lat"] = parseFloat(coords[1]);
  this.mkrData["lng"] = parseFloat(coords[0]);
  this.mkrData["alt"] = parseFloat(coords[2]);
  var point = new GLatLng(this.mrkData["lat"],this.mrkData["lng"]); 
  this.setPoint(point);
}

UserMarker.prototype.addToMap = function(map){
  map.addOverlay(this);
}

UserMarker.prototype.removeFromMap = function(map){
  map.removeOverlay(this);
}

// ******* User Marker extend GPolyLine

function LineMarker(points, xmlData, /*optional*/ color) {      
  // store the marker data
  this.mrkData = xmlData;
  // marked by mark & sweep?
  this.marked = true;
  this.selected = false;
  this.map = null;
  var iconStart = new GIcon(G_DEFAULT_ICON);
  iconStart.image = "img/icon13-green.png";
  //icon.shadow = "img/icon13.png";
  iconStart.iconSize = new GSize(32, 32);
//  icon.shadowSize = new GSize(22, 20);
  iconStart.iconAnchor = new GPoint(13, 24);
  iconStart.infoWindowAnchor = new GPoint(25, 10);
  this.startMarker = new UserMarker(points[0], this.mrkData, iconStart);  
  var iconEnd = new GIcon(G_DEFAULT_ICON);
  iconEnd.image = "img/icon13-red.png";
  //icon.shadow = "img/icon13.png";
  iconEnd.iconSize = new GSize(32, 32);
//  icon.shadowSize = new GSize(22, 20);
  iconEnd.iconAnchor = new GPoint(13, 24);
  iconEnd.infoWindowAnchor = new GPoint(25, 10);
  this.endMarker = new UserMarker(points[points.length-1],this.mrkData, iconEnd);
  this.distance = 0;  
  for(i=0; i < points.length; i++) {
    if (i+1 < points.length) {
      this.distance += points[i].distanceFrom(points[i+1]);
    }
  // TODO: declive acumulado
  // TODO: numero de pontos    
  }
  this.distance /= 1000;
  xmlData["name"] += "(" + this.distance.toFixed(2) +" km)"
  if ( color) {
    xmlData["color"] = color;
  } else {
    xmlData["color"] = colors[colorPos];
    colorPos++;
    if (colorPos >= colors.length) {
      colorPos = 0;
    }
  }  
  GPolyline.call(this, points, xmlData["color"]);        
}    

LineMarker.prototype = new GPolyline([new GLatLng(0,0)]);

LineMarker.prototype.getLatLng = function () {
  return this.startMarker.getLatLng();
}

LineMarker.prototype.setData = function(xmlData) {
  this.mrkData = xmlData;
  this.startMarker.setData(this.mrkData);
  this.endMarker.setData(this.mrkData);
  this.marked = true;
  this.visible = true;
}

LineMarker.prototype.parse = function(data){
  var allCoords = data.split(" ");                          
  var linePoints = [];           
  for ( j=0; j < allCoords.length; j++) {
    var coords = allCoords[j].split(",");                             
    linePoints.push(new GLatLng(parseFloat(coords[1]), parseFloat(coords[0])));
  } 
  this.mrkData["lat"] = linePoints[0].lat();
  this.mrkData["lng"] = linePoints[0].lng();
  this.mrkData["alt"] = 0;              
}

LineMarker.prototype.show = function() {
  GPolyline.prototype.show.apply(this);
  this.startMarker.show();
  this.endMarker.show();
  
}

LineMarker.prototype.hide = function() {
  GPolyline.prototype.hide.apply(this);
  this.startMarker.hide();
  this.endMarker.hide();
}

LineMarker.prototype.openInfoWindowHtml = function(html) {
  this.startMarker.openInfoWindowHtml(html);
}

LineMarker.prototype.getPoint = function() {
  return this.startMarker.getPoint();
}

LineMarker.prototype.addToMap = function(aMap){
  this.map = aMap;  
  this.map.addOverlay(this.startMarker);
  this.map.addOverlay(this.endMarker);
  this.map.addOverlay(this);
  if ( this.isHidden() ) {
    this.startMarker.hide();
    this.endMarker.hide();
  }
  //alert("Adicionei");
  GEvent.addListener(this.startMarker, "click", function() { showMarkerInfo2(this)});
  GEvent.addListener(this.endMarker, "click", function() { showMarkerInfo2(this)});
}

LineMarker.prototype.removeFromMap = function(aMap){
  this.map = aMap;  
  this.map.removeOverlay(this.startMarker);
  this.map.removeOverlay(this.endMarker);
  this.map.removeOverlay(this);
}

// ******* General functions....

// zoom in on a user - zooming to level 13
function zoomInOnMarker(id) {
  var mrk = userMarkers.find2(id, function(m) {
    return m.mrkData["id"];
  });
  if (mrk != null) {
    map.getInfoWindow().hide();
    map.setCenter(mrk.getPoint(), 14);
  }
}

function showMarkerInfo(marker){ 
  var html = '<div class="inmap">';
  html += '<p id="title">'+marker.mrkData["name"]+'</p>';
  html += '<dl>';
  html += '<dt>Image:</dt><dd><img src="getImage.php?id=' +  marker.mrkData["id"]+ '" alt="photo"/></dd><br/>';
  html += '<dt>Description:</dt><dd>' + marker.mrkData["desc"] + '</dd><br/>';
  html += '<dt>Latitude:</dt><dd>' + marker.mrkData["lat"] + '</dd><br/>';
  html += '<dt>Longitude:</dt><dd>' + marker.mrkData["lng"] + '</dd><br/>';
  //html += '<dt>Speed:</dt><dd>' + marker.mrkData["spd"] + '</dd><br/>';
  //html += '<dt>Heading:</dt><dd>' + marker.mrkData["hd"] + '</dd><br/>';
  html += '<dt>Altitude:</dt><dd>' + marker.mrkData["alt"] + ' m</dd><br/>';
  html += '<dt>Time:</dt><dd>' + marker.mrkData["time"] + '</dd><br/>';
  if ( marker instanceof LineMarker) {
    html += '<dt>Length:</dt><dd>' + marker.distance + ' m</dd><br/>';
    html += '<dt>Points:</dt><dd>' + marker.getVertexCount() + '</dd><br/>';
  }
  html += '</dl>';
  if (map.getZoom() <= 6) {
    html += '<p id="zoomlink"><a href="#" onclick="zoomInOnMarker(' + marker.mrkData["id"] + ')">Zoom In</a></p>';
  }
  html += '</div>';    
  marker.openInfoWindowHtml(html);                 
}

function parseDate(value) {
  var date = new Date();
  values = value.split(" ");
  ymd = values[0].split("-");
  hms = values[1].split(":");
  date.setFullYear(ymd[0]);
  date.setMonth(ymd[1]-1);
  date.setDate(ymd[2]);
  
  date.setHours(hms[0]);
  date.setMinutes(hms[1]);
  date.setSeconds(hms[2]);
  
  return date;
}

function displayLocation(marker) {
 var lat = marker.mrkData["lat"];
 if ( lat > 0 ) { 
  lat = Math.abs(lat) + "º N";
 } else {
  lat = Math.abs(lat) + "º S";
 }
 
 var lng = marker.mrkData["lng"];
 if ( lng > 0 ) { 
  lng = Math.abs(lng) + "º W";
 } else {
  lng = Math.abs(lng) + "º E";
 }
 
 return lat + "," + lng;
}

function showMarkerInfo2(marker){
  var date = marker.mrkData["time"]; 
  var html = '<div class="inmap">';
  html += '<sub>'+date.toUTCString()+'</sub>';
  html += '<p id="title">'+marker.mrkData["name"]+'</p>';
  if ( marker.mrkData["image"] != 0) {  
    html += '<center><img width="160" height="120" src="getImage.php?id=' +  marker.mrkData["image"]+ '" alt="photo"/></center>';
  }
  html += '<p>' + marker.mrkData["desc"] + '</p>';
  html += '<right><sub>' + marker.mrkData["user"] +' at ' + displayLocation(marker) + ' ' + marker.mrkData["alt"] +'m ';  
  if (map.getZoom() <= 6) {
    html += '<a href="#" onclick="zoomInOnMarker(' + marker.mrkData["id"] + ')"> Zoom In</a>';
  }
  html += '</sub></right>';
  html += '</div>';    
  marker.openInfoWindowHtml(html);                 
}

function toggleMarker(id){ 
  foundMarker = userMarkers.find2(id, function(m) {
          return m.mrkData["id"];
        });
  if ( foundMarker != null){     
	  foundMarker.selected = !foundMarker.selected;
  }
}

function openMarker(id){
  foundMarker = userMarkers.find2(id, function(m) {
          return m.mrkData["id"];
        });
  if ( foundMarker != null)
  {
    showMarkerInfo2(foundMarker);
    
  }
}

function seeUser(id) {  
  listUpdate="listPoints.php?user="+id;
  listField="name";
  updatePoints();   
}

function createDomElement(marker)
{
    // create html interface element
    var tableRow = document.createElement("tr");
    
    var tableCol1 = document.createElement("td");
    var check = document.createElement("input");
    check.setAttribute("type","checkbox");
    check.setAttribute("value",marker.mrkData["id"]);            
    if (!marker.isHidden())
    {              
      newatt=document.createAttribute("checked");
      newatt.value="true";
      check.setAttributeNode(newatt);                                          
    }            
    addMyEvent(check, "click", visibleEvent);
    
    tableCol1.appendChild(check);
    
    var tableCol2 = document.createElement("td");   
    var desc = "";
    if ( marker instanceof LineMarker)
    {
      desc = "";
    }
    var text = document.createTextNode(desc+": "+marker.mrkData["name"]);
    
    tableCol2.appendChild(text);
    
    tableRow.appendChild(tableCol1);
    tableRow.appendChild(tableCol2);
    
    return tableRow;                                   
}

function createHtmlElement(marker, field)
{
    // create html interface element    
    var tableRow = "<tr align='left'><td>";
    tableRow +="<input type='checkbox' name='markers' id='"+marker.mrkData["id"]+"' value='"+marker.mrkData["id"]+"'";            
    if (marker.selected) {              
      tableRow += " checked=true";      
    }    
    tableRow += " onclick='toggleMarker("+marker.mrkData["id"]+")'";    
    tableRow += "/>";
    var desc = " ";
    /*
    var desc = "";
    if ( marker instanceof LineMarker)
    {
      desc = "*";
    }
    */
    tableRow += "</td><td><a class='marker' href='#' onclick='this.blur();openMarker("+marker.mrkData["id"]+");'>"+desc+marker.mrkData[field]+"</a></td>";
    if ( listUpdate == 'listFriends.php'){
      tableRow +="<td><a href='#' onclick='seeUser("+ marker.mrkData["id"] +")'>(View Blog)</a></td>";
    }
    tableRow +="</tr>";            
    
    return tableRow;                                           
}

function visibleEvent(e){  
  alert(e);
  var src = null
  if(window.event) {           
    src = window.event.srcElement;    
  } else {        
    src = e.target; 
  }
  
  toggleMarker(src.value,src.checked); 
}

function addMyEvent(object, event, f){
  if (object.attachEvent) {
    object.attachEvent("on"+event, f);
  }
  else {
    object.addEventListener(event, f, false);
  }
}

function deleteMarkers(){

  var r=confirm("Are you sure you want to delete?")
  if (r==true) {    
    var markersSelected = window.document.getElementsByName("markers");
	  var toDelete = "toDelete=";
	  var count = 0;
	  for ( var i = 0; i < markersSelected.length; i++) {
	    if (markersSelected[i].checked) {
	      if ( count > 0){
	        toDelete += ",";
	      }
	      toDelete += markersSelected[i].value;
	      count++;
	    }
	  }
	  	     
	  
	  if ( count > 0) {	    
	    var request = GXmlHttp.create();
	    request.open("POST", "deletePoint.php", true);
  		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded" );                
	 	  request.setRequestHeader("Content-Length",toDelete.length );
	    request.onreadystatechange = function() {
	      if (request.readyState == 4) {
	        //alert(request.responseText);
	        //TODO: remove from list
	      }
	    }
	    request.send(toDelete);
	  }  
  }
}

function showMarkers(){
  var markersSelected = window.document.getElementsByName("markers");
  var count = 0;
  for ( var i = 0; i < markersSelected.length; i++) {
    if (markersSelected[i].checked) {      
      showMarker(markersSelected[i].value);
    }
  }     
}

function hideMarkers(){
  var markersSelected = window.document.getElementsByName("markers");
  var count = 0;
  for ( var i = 0; i < markersSelected.length; i++) {
    if (markersSelected[i].checked) {      
      hideMarker(markersSelected[i].value);
    }
  }     
}

function showMarker(id) { 
  foundMarker = userMarkers.find2(id, function(m) {
          return m.mrkData["id"];
        });
  if ( foundMarker != null) {     
      if (foundMarker.isHidden()) {
        foundMarker.show();
      }   
  }
}

function hideMarker(id) { 
  foundMarker = userMarkers.find2(id, function(m) {
          return m.mrkData["id"];
        });
  if ( foundMarker != null) {     
      if (!foundMarker.isHidden()) {
        foundMarker.hide();
      }   
  }
}

function selectAllMarkers(select){
  var markersSelected = window.document.getElementsByName("markers");
  var count = 0;  
  for ( var i = 0; i < markersSelected.length; i++) {
    markersSelected[i].checked = select;   
  }
  userMarkers.forEach(function(m) {
          return m.selected=select;
        });     
}

function parseMarkersKml(xml) {                                               
      markersBounds = new GLatLngBounds();
      // sweep
      userMarkers.forEach(function(m) {
        m.marked = false;             
      });
         
      // Parse Markers
      var placemarks = xml.documentElement.getElementsByTagName("FindMePlacemark");
      if ( placemarks.length > 0) {
         for (var i = 0; i < placemarks.length; i++) {
           var marker = parseMarker(placemarks[i]);
           markersBounds.extend(marker.getLatLng());           
         }                                                 
         // sweep
         userMarkers.lastForEach(function(m) {
           if (!m.marked) {
             userMarkers.remove(m);
             m.removeFromMap(map);              
           }
         });          
      }      
      userMarkers.sort(function(a,b){return b.mrkData["time"]-a.mrkData["time"]});
}

function parseMarker(placemark){
      var marker = null;
      var xmlData = new Array();
      xmlData["id"] = placemark.getAttribute("id");
      xmlData["name"] = placemark.getElementsByTagName("name")[0].childNodes[0].data;
      xmlData["time"] = parseDate(placemark.getElementsByTagName("date")[0].childNodes[0].data);
      if (placemark.getElementsByTagName("image")[0].childNodes.length > 0) {
        xmlData["image"] = placemark.getElementsByTagName("image")[0].childNodes[0].data;
      } else {
        xmlData["image"] = 0;
      }
      xmlData["user"] = placemark.getElementsByTagName("user")[0].childNodes[0].data;
      if (placemark.getElementsByTagName("description")[0].childNodes.length > 0) {
        xmlData["desc"] = placemark.getElementsByTagName("description")[0].childNodes[0].data;
      }else {
        xmlData["desc"] ='';
      }
      if ( placemark.getElementsByTagName("Point").length > 0){
        // is a point
        var coords = placemark.getElementsByTagName("Point")[0].getElementsByTagName("coordinates")[0].childNodes[0].data.split(",");                      
        xmlData["lat"] = parseFloat(coords[1]);
        xmlData["lng"] = parseFloat(coords[0]);
        xmlData["alt"] = parseFloat(coords[2]);
        var point = new GLatLng(xmlData["lat"],xmlData["lng"]);          
        
        // find marker                                  
        marker = userMarkers.find2(xmlData["id"], function(m) {
            return m.mrkData["id"];
          });                
                      
        if (marker == null) {
          marker = new UserMarker(point);                
          userMarkers.push(marker);
          map.addOverlay(marker);
          GEvent.addListener(marker, "click", function() { showMarkerInfo2(this)});                              
        }
        marker.setData(xmlData);
        marker.setPoint(point);
        
      } else if (placemark.getElementsByTagName("LineString").length > 0) {
        // is a line
        var allCoords = placemark.getElementsByTagName("LineString")[0].getElementsByTagName("coordinates")[0].childNodes[0].data.split(" ");                          
        var linePoints = [];           
        for ( j=0; j < allCoords.length-1; j++){
          var coords = allCoords[j].split(",");                             
          linePoints.push(new GLatLng(parseFloat(coords[1]), parseFloat(coords[0])));
        }        
        xmlData["lat"] = linePoints[0].lat();
        xmlData["lng"] = linePoints[0].lng();
        xmlData["alt"] = 0;              
          // find marker
        var foundMarker = null;
                    
        foundMarker = userMarkers.find2(xmlData["id"], function(m) {
            return m.mrkData["id"];
          });
        if (foundMarker){
          marker = new LineMarker(linePoints, xmlData, foundMarker.mrkData["color"]);
        } else {                                                    
          marker = new LineMarker(linePoints, xmlData);
        }    
        marker.setData(xmlData);
        userMarkers.push(marker);        
        if (foundMarker){ 
          if ( foundMarker.isHidden()) {
            marker.hide();
          }
          marker.selected = foundMarker.selected;
        }
        marker.addToMap(map);                                                                                                                                              
      }
      
      return marker;                                                     
    }
